package com.lanou.userLogin.user.web.servlet;

import com.lanou.userLogin.cart.domin.CartItem;
import com.lanou.userLogin.user.domain.User;
import com.lanou.userLogin.user.service.UserLoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userLoginServlet")
public class UserLoginServlet extends HttpServlet {

    private UserLoginService uls = new UserLoginService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        User login = uls.login(user);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        List<CartItem> cartItemList = new ArrayList<>();
        if (login.getUsername() == null && login.getPassword() == null) {
            pw.write("登录失败，3秒后返回登录界面");
            resp.setStatus(302);
            resp.setHeader("refresh", "3;/jsps/user/login.jsp");
        } else {
            HttpSession session = req.getSession();
            session.setAttribute("cartItemList", cartItemList);
            session.setMaxInactiveInterval(100000000);
            session.setAttribute("username", username);
            //System.out.println(login.getUid());
            session.setAttribute("uid", login.getUid());
            req.getRequestDispatcher("/jsps/main.jsp").forward(req, resp);
        }
    }
}
